<template>
  <div class="register">
    <div class="content">
      <div class="title">注册</div>
      <el-form label-position="top" size="large" ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item label="用户名" prop="nickname">
          <el-input v-model="ruleForm.nickname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item class="btns">
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </el-form-item>
      </el-form>
      <div class="tips">
        已有账号?
        <router-link class="link" to="/login">去登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { register } from "~/api/login/index";
// init
const router = useRouter();
const ruleForm = reactive({ nickname: "", password: "" });
const ruleFormRef = ref();
// 自定义验证密码
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (ruleForm.password !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("checkPass", () => null);
    }
    callback();
  }
};
const rules = reactive({
  nickname: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ validator: validatePass, trigger: "blur" }],
});
// 重置表单
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
};
// 提交表单
const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate();
  await register(ruleForm);
  ElMessage({ message: "注册成功", type: "success" });
  router.push("/login");
};
</script>

<style lang="scss" scoped>
.register {
  @include flexCenter;
  height: 100%;
  background: url("@/assets/images/bg-img.jpg") no-repeat 100% 100% / cover;
  .content {
    width: 400px;
    background-color: rgba(#fff, 0.36);
    border-radius: $radius;
    padding: $padding;
    .title {
      font-size: 20px;
      font-weight: bold;
      padding: 8px 0;
      text-align: center;
    }
    .btns {
      margin-top: 48px;
      :deep(.el-form-item__content) {
        width: 100%;
        @include flexAlignCenter;
        justify-content: flex-end;
        button {
          width: 100px;
          &:last-child {
            margin-left: 40px;
          }
        }
      }
    }
    .tips {
      text-align: center;
      color: $color-subtitle;
      .link {
        color: $primary-color;
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}
</style>
